package main

import (
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings"

	"github.com/gorilla/mux"
)

const PORT = 8000

func proxyFunc(proxyUrl string, path string) (http.HandlerFunc, error) {
	remote, err := url.Parse(proxyUrl) // 替换为你的目标URL
	if err != nil {
		return nil, err
	}

	proxy := httputil.NewSingleHostReverseProxy(remote)
	proxy.Director = func(req *http.Request) {

		req.Host = remote.Host
		req.URL.Scheme = remote.Scheme
		req.URL.Host = remote.Host
		req.URL.Path = path
	}
	return proxy.ServeHTTP, nil
}

func proxyCommon(name, path string) (http.HandlerFunc, error) {
	if path == "" {
		path = "/"
	}
	//name split : port
	namePort := strings.Split(name, ":")
	host := namePort[0]
	port := "80"
	schema := "http"
	if len(namePort) == 3 {
		schema = namePort[0]
		host = namePort[1]
		port = namePort[2]
	}
	if len(namePort) == 2 {
		host = namePort[0]
		port = namePort[1]
	}
	if len(namePort) == 1 {
		host = namePort[0]
	}
	proxyUrl := schema + "://" + host + ":" + port
	slog.Info("proxyUrl:" + proxyUrl + "porxyPath" + path)
	return proxyFunc(proxyUrl, "/"+path)
}

func parseHost(host string) string {
	splitHost := strings.Split(host, "-")
	scheme := splitHost[0]
	port := splitHost[len(splitHost)-1]
	ip := splitHost[1 : len(splitHost)-1]
	proxyIp := strings.Join(ip, ".")
	proxyServer := scheme + "://" + proxyIp + ":" + port
	return proxyServer
}

func main() {
	// if true {
	// 	u := parseHost("http-118-25-145-25-9999")
	// 	fmt.Println(u)
	// 	return
	// }
	// if true {
	// 	os.Setenv("APP_KEY", "base64:bxv+Iol90rLj+ntDjTlzqUxBn3O8vALpWB6pBgh/kkE=")
	// 	str := "eyJpdiI6IkNWaTdTcFRURERyN3J1QVRScGI0YkE9PSIsInZhbHVlIjoiMGF0cTZiUHhJYXJuT2pBcHhXL1Y4bDMzb1U3azIvbllxclFPL1dqY1lPdz0iLCJtYWMiOiI5YzI4MGU4ZGE0YWEyMGFmMjUxMDBlNTc5Yjk1NDE1YWEzNzFiNzcwNTI2YTVkNjJhYmE5NjRjNzk0ZDFiZjI1IiwidGFnIjoiIn0="
	// 	fmt.Println("xxxxxxx")
	// 	fmt.Println(Decrypt(str))
	// 	return
	// }

	r := mux.NewRouter()

	// 定义路由，使用 {proxyServer} 和 {path} 作为占位符
	r.HandleFunc("/k8s/v1/{proxyServer}/proxy/{path:.*}", func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		proxyServer := vars["proxyServer"]
		path := vars["path"]
		fmt.Println("proxyServer:" + proxyServer)

		proxyFunc, err := proxyCommon(proxyServer, path)
		if err != nil {
			fmt.Println("Failed to orixt the server:", err)
			http.Error(w, "Invalid request path", http.StatusBadRequest)
			return
		}
		proxyFunc(w, r)
	})

	r.HandleFunc("/{path:.*}", func(w http.ResponseWriter, r *http.Request) {
		//获取当前的域名 https://http-127-0-0-1-80/
		vars := mux.Vars(r)
		path := vars["path"]
		host := r.Host
		fmt.Println("host:" + host)
		first := strings.Split(host, ".")[0]

		proxyServer := parseHost(first)
		proxyFunc, err := proxyFunc(proxyServer, "/"+path)
		if err != nil {
			fmt.Println("Failed to orixt the server:", err)
			http.Error(w, "Invalid request path", http.StatusBadRequest)
			return
		}
		proxyFunc(w, r)
	})
	// http.Handle("/", r)

	fmt.Println("Listening on port", PORT)

	err := http.ListenAndServe(fmt.Sprintf(":%d", PORT), r)
	if err != nil {
		fmt.Println("Failed to start the server:", err)
	}
}
